import { loginAPI, getUserInfoAPI, getUserDetailByIdAPI } from '@/api'

import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'

// 状态
const state = {
  token: getToken() || {},
  userInfo: null
}
// 修改状态
const mutations = {
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
// 执行异步
const actions = {
  async loginInfo(context, data) {
    const res = await loginAPI(data)
    // console.log(res)

    context.commit('setToken', res)
    setTimeStamp()
  },
  async getUserInfo(context) {
    const res = await getUserInfoAPI()
    const res2 = await getUserDetailByIdAPI(res.userId)
    context.commit('setUserInfo', { ...res, ...res2 })
  },
  // async getUserInfo(context) {
  //   const res = await getUserInfoAPI()
  //   context.commit('setUserInfo', res)
  // },
  // 获取用户资料action
  // async getUserInfo(context) {
  //   const res = await getUserInfoAPI() // result就是用户的基本资料
  //   const baseInfo = await getUserDetailByIdAPI(res.userId) // 为了获取头像
  //   const baseResult = { ...res, ...baseInfo } // 将两个接口结果合并
  //   // 此时已经获取到了用户的基本资料 迫不得已 为了头像再次调用一个接口
  //   context.commit('setUserInfo', baseResult) // 提交mutations
  //   // 加一个点睛之笔  这里这一步，暂时用不到，但是请注意，这给我们后边会留下伏笔
  //   return baseResult
  // }
  async logout(context) {
    context.commit('setToken', null)
    removeToken()
    context.commit('setUserInfo', null)
  }

}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
